<?php

namespace app\common\controller;

use app\BaseController;
use app\model\ConfigModel;
use app\model\DepartmentAdminModel;
use app\model\DepartmentLevelModel;
use app\model\LogModel;
use app\model\UnitBannerModel;
use app\model\UnitModel;
use app\model\UserModel;
use app\socket\Server;
use think\App;
use app\model\DepartmentModel;
use think\swoole\Websocket;

class Config extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new ConfigModel();
    }

    /**
     * 更新修改系统设置参数
     * @return false|string
     */
    public function update(Websocket $websocket): bool|string
    {
        $param = $this->request->param();
        $this->mode->startTrans();
        try {
            $this->validate($param, $this->mode->addValidate());
            $type = $param['value']['type'] ?? 0;
            $param['value'] = json_encode($param['value'], true);
            $param['time'] = time();
            $info = $this->mode->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => $param['key']
            ])->find();
            if (!$info) {
                $param['unit_id'] = $this->userData['unit_id'];
                $this->mode->insert($param);
            } else {
                $data = json_decode($info['value'], true);
                //部门管理方式【1非学院，2 学院制】
                if ($param['key'] == 'department_management' && @$data['type'] != $type) {
                    //部门
                    $DepartmentModel = new DepartmentModel();
                    $DepartmentIds = $DepartmentModel->where('unit_id', '=', $this->userData['unit_id'])->column('id');
                    $DepartmentModel->where('unit_id', '=', $this->userData['unit_id'])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //部门管理
                    $DepartmentAdminModel = new DepartmentAdminModel();
                    $DepartmentAdminModel->where('department_id', 'in', $DepartmentIds)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //普通用户
                    $UserModel = new UserModel();
                    $UserModel->where([
                        ['unit_id', '=', $this->userData['unit_id']],
                        ['role_mode', '=', 3]
                    ])->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                }
                $info->save($param);
            }
            $this->mode->commit();
            //推送socket消息
            $UserModel = new UserModel();
            $uid = $UserModel->where('unit_id', '=', $this->userData['unit_id'])->column('id');
            if (!empty($uid)){
                $socketServer = new Server();
                $fd = $socketServer->uidGetFd($uid);
                if (!empty($fd)){
                    $socketServer->push($fd, json_encode([
                        'type' => 'config',
                        'content' => [
                            'key' => $param['key'],
                            'value' => json_decode($param['value'],true)
                        ]
                    ]), $websocket);
                }
            }
            return success([], '更新成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取系统设置参数
     * @return bool|string
     */
    public function getConfig(): bool|string
    {
        $param = $this->request->param();
        try {
            $this->validate($param, $this->mode->getValidate());
            $data = $this->mode->where([
                'unit_id' => $this->userData['unit_id'],
                'key' => $param['key']
            ])->value('value') ?? '';
            $data = json_decode($data, true);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取部门升级规则模板
     * @return bool|string
     */
    public function getDepartmentLevelModel(): bool|string
    {
        $data = [
            [
                'name' => '九年义务教育',
                'level_rules' => ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级', '七年级', '八年级', '九年级']
            ],
        ];
        return success($data);
    }

    /**
     * 添加部门等级规则
     * @return false|string
     */
    public function addDepartmentLevel(): bool|string
    {
        try {
            $param = $this->request->param();
            $DepartmentLevelModel = new DepartmentLevelModel();
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $this->validate($param, $DepartmentLevelModel->addValidate());
            $param['time'] = time();
            $DepartmentLevelModel->insert($param);
            return success([], '添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 编辑部门等级规则
     * @return false|string
     */
    public function updateDepartmentLevel(): bool|string
    {
        try {
            $param = $this->request->param();
            $DepartmentLevelModel = new DepartmentLevelModel();
            $info = $DepartmentLevelModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
//            if (isset($param['status']) && $param['status'] == 0) {
                $DepartmentModel = new DepartmentModel();
                $is_use_model = $DepartmentModel->where('mode', '=', $param['id'])->value('id');
                if ($is_use_model) throw new \Exception('此等级规则在使用中无法修改！');
//            }
            $info->save($param);
            return success([], '更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 删除部门等级规则
     * @return false|string
     */
    public function delDepartmentLevel(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $DepartmentLevelModel = new DepartmentLevelModel();
            $info = $DepartmentLevelModel->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $DepartmentModel = new DepartmentModel();
            $is_use_model = $DepartmentModel->where('mode', '=', $id)->value('id');
            if ($is_use_model) throw new \Exception('此等级规则在使用中无法删除！');
            $info->is_del = 1;
            $info->del_time = time();
            $info->save();
            return success([], '删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门等级规则列表
     * @return false|string
     */
    public function departmentLevelList(): bool|string
    {
        try {
            $DepartmentLevelModel = new DepartmentLevelModel();
            $list = $DepartmentLevelModel->where('unit_id', '=', $this->userData['unit_id'])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取部门等级规则详情
     * @return false|string
     */
    public function getDepartmentLevelInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $DepartmentLevelModel = new DepartmentLevelModel();
            return success($DepartmentLevelModel->find($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 设置单位信息
     * @return false|string
     */
    public function setUnitInfo(): bool|string
    {
        $unitData = $this->request->param('unit');
        $pc_banner = $this->request->param('pc_banner');
        $mobile_banner = $this->request->param('mobile_banner');
        $UnitModel = new UnitModel();
        $UnitBanner = new UnitBannerModel();
        $UnitModel->startTrans();
        try {
            if (!empty($pc_banner)) {
                $pc_bannerData = [];
                foreach ($pc_banner as $item) {
                    if (empty($item)) continue;
                    $pc_bannerData[] = [
                        'unit_id' => $this->userData['unit_id'],
                        'type' => 1,
                        'img' => $item,
                        'time' => time()
                    ];
                }
                $UnitBanner->where([
                    'unit_id' => $this->userData['unit_id'],
                    'type' => 1
                ])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $UnitBanner->insertAll($pc_bannerData);
            }
            if (!empty($mobile_banner)) {
                $mobile_bannerData = [];
                foreach ($mobile_banner as $item) {
                    if (empty($item)) continue;
                    $mobile_bannerData[] = [
                        'unit_id' => $this->userData['unit_id'],
                        'type' => 2,
                        'img' => $item,
                        'time' => time()
                    ];
                }
                $UnitBanner->where([
                    'unit_id' => $this->userData['unit_id'],
                    'type' => 2
                ])->update([
                    'is_del' => 1,
                    'del_time' => time()
                ]);
                $UnitBanner->insertAll($mobile_bannerData);
            }
            $UnitModel->where('id', '=', $this->userData['unit_id'])->update($unitData);
            $UnitModel->commit();
            return success([], '修改成功！');
        } catch (\Exception $e) {
            $UnitModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取单位信息
     * @return false|string
     */
    public function getUnitInfo(): bool|string
    {
        try {
            $UnitModel = new UnitModel();
            $UnitBannerModel = new UnitBannerModel();
            $info = $UnitModel->find($this->userData['unit_id']);
            $pc_banner = $UnitBannerModel->where([
                'unit_id' => $this->userData['unit_id'],
                'type' => 1
            ])->column('img');
            $mobile_banner = $UnitBannerModel->where([
                'unit_id' => $this->userData['unit_id'],
                'type' => 2
            ])->column('img');
            return success(['info' => $info, 'pc_banner' => $pc_banner, 'mobile_banner' => $mobile_banner]);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 系统日志
     * @return bool|string
     */
    public function LogList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $UserModel = new UserModel();
            if (!empty($param['name']) && !empty($param['department_id'])) {
                $uid = $UserModel->where([
                    ['name', 'like', '%' . $param['name'] . '%'],
                    ['department_id', '=', $param['department_id']],
                ])->column('id');
                if (count($uid) > 0) {
                    $where[] = ['uid', 'in', $uid];
                } else {
                    $where[] = ['id', '=', -1];
                }
            } else {
                if (!empty($param['department_id'])) {
                    $uid = $UserModel->where('department_id', '=', $param['department_id'])->column('id');
                    if (count($uid) > 0) {
                        $where[] = ['uid', 'in', $uid];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
                if (!empty($param['name'])) {
                    $uid = $UserModel->where('name', 'like', '%' . $param['name'] . '%')->column('id');
                    if (count($uid) > 0) {
                        $where[] = ['uid', 'in', $uid];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['ua'])) {
                $where[] = ['ua', 'like', '%' . $param['ua'] . '%'];
            }
            if (!empty($param['type'])) {
                $where[] = ['type', 'in', $param['type']];
            }
            $where[] = match ($this->userData['type']) {
                1 => ['company_id', '=', $this->userData['company_id']],
                2 => ['areas_id', '=', $this->userData['areas_id']],
                3 => ['unit_id', '=', $this->userData['unit_id']],
                default => ['uid', '=',  $this->userData['id']],
            };
            $LogModel = new LogModel();
            $data = $LogModel->where($where)->with(['userName'])->order('id desc')->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 部门选择器
     * @return bool|string
     */
    public function DepartmentSelector(): bool|string
    {
        try {
            $DepartmentModel = new DepartmentModel();
            $data = $DepartmentModel->where('unit_id', '=', $this->userData['unit_id'])->field('id,pid,name')->select()->toArray();
            return success(buildTree($data));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 学院制【到期自动升级】
     * @return bool|string
     */
//    public function graduate(): bool|string
//    {
//        try {
//            $UnitModel = new UnitModel();
//            $userMode = new UserModel();
//            $ConfigService = new ConfigService($this->app);
//            $department_level = new DepartmentLevelModel();
//            $departmentModel = new DepartmentModel();
//
//            $unit_list = $UnitModel->column('id');
//            foreach($unit_list as $item){
//                $config = $ConfigService->getConfig($item,'department_management');
//                if($config['type'] != 2) continue;
//                //获取设置的升级日期
//                $expiration_date = strtotime(date('Y-'.$config['upgrade_time_month'].'-'.$config['upgrade_time_day']));
//                //判断是否要自动升级【大于等于设置的时间戳】
//                if(time() < 1738890513) continue;
//                /**
//                 * 开始自动升级处理数据
//                 * 1.判断是不是升级到最后一级
//                 *      1.1:没到最后，
//                 *          1.1.1：【部门表】升一级（stage+1），
//                 *          1.1.2：【部门表】更改部门的名称为升级之后的名称
//                 *      1.2:到最后【判断设置：毕业后用户处理（end_status==1：直接删除用户所有资料）、==2：保留资料】，
//                 *          1.2.1：判断end_status的值，
//                 *              1.2.2.1：（等于1：删除资料）
//                 *                  一、【所有与用户相关的表的资料】删除用户：（删除语句）
//                 *                  -----其他的表（与用户相关的表）一样处理------
//                 *              1.2.2.2：（等于2：保留资料）
//                 *                  一、【用户表】修改用户的学籍状态：改为毕业（student_status==2）
//                 *                  二、【用户表】修改用户的账号状态：改为禁止登录（status==2）
//                 *                  三、【用户表】修改用户的账号状态：改为已删除（is_del==1）
//                 *                  -----其他的表（与用户相关的表）一样处理------
//                 *          1.2.2：【部门表】删除这个部门（id_del==1），
//                 *          1.2.3：【部门管理员表】删除这个部门管理员（id_del==1），
//                 *
//                 * */
//                //查询学制阶段的数据【如果单位内有多个规则，循环处理】
//                $department_level_info = $department_level->where([['unit_id','=',$item],['status','=','1']])->field('id,level_rules')->select();
//                $temp_department_level_info = [];
//                foreach($department_level_info->toArray() as &$value){
//                    $value['level_rules'] = json_decode($value['level_rules']);
//                    $value['level_count'] = count($value['level_rules']);
//                    $temp_department_level_info[$value['id']] = $value;
//                }
//                //查询单位内所有得部门
//                $departmentInfo = $departmentModel->where([['unit_id','=',$item],['level','=',2]])->field('id,level,name,mode,stage')->select();
//                if(count($departmentInfo)>0){
//                    foreach ($departmentInfo->toArray() as $v){
//                        //获取当前部门层级得学制阶段信息
//                        $level_rule = $temp_department_level_info[$v['mode']];
//                        //判断是不是升级到最后一级
//                        if($v['stage'] < $level_rule['level_count']){//不是最后一级
//                            $new_stage = $v['stage']+1;
//                            $update = [
//                                'stage'=>$new_stage,
//                                'name'=>$temp_department_level_info[$v['mode']]['level_rules'][$new_stage],
//                            ];
//                            $departmentModel->where('id',$v['id'])->update($update);
//                        }else{//是最后一级
//                            //获取要操作得所有用户id
//                            $ids = $userMode->where([['department_id','=',$v['id']]])->column('id');
//                            if($ids){
//                                if($config['end_status'] == 2){//保留资料
//                                    //修改普通用户信息
//                                    $userUpdate = [
//                                        'student_status'=>2,
//                                        'status'=>2,
//                                        'is_del'=>1,
//                                        'del_time'=>time(),
//                                    ];
//                                    $userMode->where(['department_id','=',$v['id']])->update($userUpdate);
//                                    $tempUpdate = [
//                                        'is_del'=>1,
//                                        'del_time'=>time(),
//                                    ];
//                                    //开始伪删除与用户相关得数据
//                                    ConsultBlacklistModel::query()->where('uid','in',$ids)->update($tempUpdate);//心理咨询-黑名单表
//                                    ConsultOfflineModel::query()->where('uid','in',$ids)->update($tempUpdate);//线下咨询表
//                                    ConsultOfflineResultModel::query()->where('uid','in',$ids)->update($tempUpdate);//线下咨询量表测评结果表
//                                    ConsultOnlineModel::query()->where('uid','in',$ids)->update($tempUpdate);//线上咨询表
//                                    ConsultOnlineMessageModel::query()->where([['uid','in',$ids],['who','=',1]])->update($tempUpdate);//线上咨询内容表
//                                    ConsultOnlineResultModel::query()->where('uid','in',$ids)->update($tempUpdate);//线上咨询量表测评结果表
//                                    CrisisLogModel::query()->where('uid','in',$ids)->update($tempUpdate);//危机干预-消息记录盒表
//                                    CrisisUserModel::query()->where('uid','in',$ids)->update($tempUpdate);//危机用户（危机上报）表
//                                    FollowUserModel::query()->where('uid','in',$ids)->update($tempUpdate);//关注用户（关注人群）表
//                                    InterfereUserModel::query()->where('uid','in',$ids)->update($tempUpdate);//干预人群表
//                                    InterpretationRecordModel::query()->where('uid','in',$ids)->update($tempUpdate);//申请解读记录表
//                                    LogModel::query()->where('uid','in',$ids)->update($tempUpdate);//系统日志表
//                                    LoginLogModel::query()->where('uid','in',$ids)->update($tempUpdate);//用户登录日志表
//                                    MessageModel::query()->where('uid','in',$ids)->update($tempUpdate);//用户接收的消息表
//                                    ProxyEvaluationResultModel::query()->where('uid','in',$ids)->update($tempUpdate);//代理测评结果（他人代测）表
//                                    SelfEvaluationResultModel::query()->where('uid','in',$ids)->update($tempUpdate);//自我测评结果表
//                                    TaskUserModel::query()->where('uid','in',$ids)->update($tempUpdate);//测评任务用户表
//                                    TaskUserResultModel::query()->where('uid','in',$ids)->update($tempUpdate);//任务用户答题结果表
//                                    TaskUserResultContinuityModel::query()->where('uid','in',$ids)->update($tempUpdate);//任务用户答题结果（因子预警连续测评）表
//                                    UserArchiveModel::query()->where('uid','in',$ids)->update($tempUpdate);//用户档案表
//                                    WarningReportRecordModel::query()->where('uid','in',$ids)->update($tempUpdate);//预警报告记录
//                                    $userMode->where('id','in',$ids)->update($tempUpdate);
//                                    //伪删除部门及部门里得管理员
//                                    DepartmentAdminModel::query()->where('department_id',$v['id'])->update($tempUpdate);
//                                    $departmentModel->where('id',$v['id'])->update($tempUpdate);
//                                }else{//删除资料
//                                    //开始删除与用户相关得数据
//                                    ConsultBlacklistModel::query()->where('uid','in',$ids)->delete();//心理咨询-黑名单表
//                                    ConsultOfflineModel::query()->where('uid','in',$ids)->delete();//线下咨询表
//                                    ConsultOfflineResultModel::query()->where('uid','in',$ids)->delete();//线下咨询量表测评结果表
//                                    ConsultOnlineModel::query()->where('uid','in',$ids)->delete();//线上咨询表
//                                    ConsultOnlineMessageModel::query()->where([['uid','in',$ids],['who','=',1]])->delete();//线上咨询内容表
//                                    ConsultOnlineResultModel::query()->where('uid','in',$ids)->delete();//线上咨询量表测评结果表
//                                    CrisisLogModel::query()->where('uid','in',$ids)->delete();//危机干预-消息记录盒表
//                                    CrisisUserModel::query()->where('uid','in',$ids)->delete();//危机用户（危机上报）表
//                                    FollowUserModel::query()->where('uid','in',$ids)->delete();//关注用户（关注人群）表
//                                    InterfereUserModel::query()->where('uid','in',$ids)->delete();//干预人群表
//                                    InterpretationRecordModel::query()->where('uid','in',$ids)->delete();//申请解读记录表
//                                    LogModel::query()->where('uid','in',$ids)->delete();//系统日志表
//                                    LoginLogModel::query()->where('uid','in',$ids)->delete();//用户登录日志表
//                                    MessageModel::query()->where('uid','in',$ids)->delete();//用户接收的消息表
//                                    ProxyEvaluationResultModel::query()->where('uid','in',$ids)->delete();//代理测评结果（他人代测）表
//                                    SelfEvaluationResultModel::query()->where('uid','in',$ids)->delete();//自我测评结果表
//                                    TaskUserModel::query()->where('uid','in',$ids)->delete();//测评任务用户表
//                                    TaskUserResultModel::query()->where('uid','in',$ids)->delete();//任务用户答题结果表
//                                    TaskUserResultContinuityModel::query()->where('uid','in',$ids)->delete();//任务用户答题结果（因子预警连续测评）表
//                                    UserArchiveModel::query()->where('uid','in',$ids)->delete();//用户档案表
//                                    WarningReportRecordModel::query()->where('uid','in',$ids)->delete();//预警报告记录
//                                    $userMode->where('id','in',$ids)->delete();
//                                    //删除部门及部门里得管理员
//                                    DepartmentAdminModel::query()->where('department_id',$v['id'])->delete();
//                                    $departmentModel->where('id',$v['id'])->delete();
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//            return success();
//        }catch (\Exception $e){
//            return error($e->getMessage(),$e->getCode(),[
//                'file' => $e->getFile(),
//                'line' => $e->getLine()
//            ]);
//        }
//    }

}

